"""
Project Cli - Command line interface for AgentProxy to control Android devices through LLM by adb
"""

import click
import rich
import asyncio
from rich.console import Console
import os

console = Console()

# 自定义的装饰器，用于将异步函数转换为同步函数
def coro(func):
    def wrapper(*args, **kwargs):
        return asyncio.run(func(*args, **kwargs))
    return wrapper

# action执行的方法
@coro
async def run_command(command: str,device: str | None,provider : str , model : str, vision : bool ,base_url : str) :
    """
    对接用户，接收将意图命令command,交给provider(负责与LLM的交互)处理，同时需要操作设备的(获取UI元素信息、执行对应的设备操作等等)，provider通过adb与device交互。
    Args:
        command (str): The command to run.
        device 
    Des:
        有2个关键class，一个reason和一个reaction。    
    """
    # TODO 
    console.print(f"[bold blue]开始执行命令:[/bold yellow] {command}")

    """     
    操作provider和model
    根据provider从环境变量获取API_KEY
    如果没有指定provider，则使用默认的provider
    如果没有指定model，则使用默认模型 
    """
    
    if(vision):
        console.print("[blue]Vision capabilities are enabled.[/]")
    else:
        console.print("[blue]Vision capabilities are disabled.[/]")

    api_key = None
    if provider.lower() == 'openai':
        api_key = os.environ.get('OPENAI_API_KEY')
        if not api_key:
            console.print("[red]OpenAI API key not found in environment variables.[/]")
            return
        if not model:
            model = 'gpt-4o-mini'
    elif provider.lower() == 'ollama':
        api_key = os.environ.get('OLLAMA_API_KEY')
        if not api_key:
            console.print("[red]Ollama API key not found in environment variables.[/]")
            return
        if not model:
            model = 'llama3'
    """ 操作设备device """
    try:
        if not device:
            # 获取设备
            # devices = 
            return
    except Exception as e:
        console.print(f"[red]Error while running command: {e}[/]")
        return

    """ 初始化LLMReasoner """

    """ 初始化回调行为执行者ReActAgent """

    """ 添加异常处理 """


## start 有关命令行入口 和 参数选项配置的功能开发

# 定义对象Class AgentProxyCli(click.group),自定义命令行执行逻辑
class AgentProxyCli(click.Group):
    def parse_args(self,ctx,args):
        if args and not args[0].startswith('-') and args[0] not in self.commands:
            # 如果第一个参数不是选项，则将其作为命令
            args.insert(0, 'run')
        return super().parse_args(ctx, args)

# TODO 定义一个函数，被@click.group()装饰器函数注解;代表命令的通用入口，定义命令组
@click.group(cls=AgentProxyCli, help="AgentProxy CLI - Control Android devices using LLMs")
def cli():
    """AgentProxy Command Line Interface"""
    pass

# 定义一个函数，被@cli.command()装饰器函数注解;代表命令的具体实现，将命令的参数和选项传递给具体实现的run_command函数
@cli.command(help="Run a command on your Android device using natural language.")
@click.argument('command', type=str, required=True)
@click.option('--device', '-d', type=str, help='The device to run the command on.')
@click.option('--provider', '-p', type=str, default='openai', help='The LLM provider (openai, ollama, anthropic, gemini).')
@click.option('--model', '-m', type=str, default='gpt-3.5-turbo', help='The LLM model name.')
@click.option('--steps', '-s', type=int, default=5, help='Maximum number of steps.')
@click.option('--vision', '-v', is_flag=True, help='Enable vision capabilities.')   
@click.option('--base-url', '-b', type=str, default='none', help='Base URL for API (e.g., OpenRouter or Ollama).')
def run(command : str, device: str | None, provider: str, model: str, steps: int, vision: bool, base_url: str):
    """Run a command on your Android device using natural language.
        Args:
            command (str): The command to run.（nature language with promote for Action）
            device (str | None): The device serial number or IP address.
            provider (str): The LLM provider (openai, ollama, anthropic, gemini).
            model (str): The LLM model name.
            steps (int): Maximum number of steps.
            vision (bool): Enable vision capabilities.
            base_url (str): Base URL for API (e.g., OpenRouter or Ollama).
        Return:
    """
    return run_command(command, device, provider, model, vision, base_url)
